package com.lagou.service;

import com.lagou.JSONSerializer;
import com.lagou.handler.RpcDecoder;
import com.lagou.handler.UserServiceHandler;
import com.lagou.model.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService, DisposableBean {
    private Channel channel;

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;

    //将来客户单要远程调用的方法
    public String sayHello(String msg) {
        System.out.println("are you ok ? " + msg);
        return "服务器返回数据 : " + msg;
    }

    //创建一个方法启动服务器
    public void startServer(int port) throws InterruptedException {
        //1.创建两个线程池对象
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        if (!channelFuture.isSuccess()) {
            System.out.println("error");
        }
        channel = channelFuture.channel();
    }

    @Override
    public void destroy() throws Exception {
        channel.close();
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
